﻿package mortal.game.scene3D.ai.ais
{
    import flash.utils.*;
    import mortal.game.cache.*;
    import mortal.game.events.*;
    import mortal.game.mvc.*;
    import mortal.game.resource.*;
    import mortal.game.scene3D.ai.*;
    import mortal.game.scene3D.ai.base.*;
    import mortal.game.scene3D.layer3D.utils.*;
    import mortal.game.scene3D.player.entity.*;
    import mortal.mvc.core.*;

    public class ClickNpcAI extends AICommand
    {
        private var _turnTimerId:int = -1;

        public function ClickNpcAI()
        {
            return;
        }// end function

        override public function get stopable() : Boolean
        {
            return false;
        }// end function

        override public function start(param1:Function = null) : void
        {
            super.start(param1);
            ThingUtil.selectEntity = ThingUtil.npcUtil.getNpc(int(data.params));
            if (ThingUtil.selectEntity == null)
            {
                this.stop(false);
                return;
            }
            if (!GameDefConfig.instance.isDoNotTargetToPlayer(int(data.params)))
            {
                (ThingUtil.selectEntity as NPCPlayer).updateIsTalkToRole(true);
            }
            if (this._turnTimerId > 0)
            {
                clearTimeout(this._turnTimerId);
                this._turnTimerId = -1;
            }
            this._turnTimerId = setTimeout(this.nextFrame, 200);
            return;
        }// end function

        private function nextFrame() : void
        {
            if (AIManager.curAI != this)
            {
                if (ThingUtil.selectEntity is NPCPlayer)
                {
                    (ThingUtil.selectEntity as NPCPlayer).updateIsTalkToRole(false);
                }
                return;
            }
            if (ThingUtil.selectEntity == null)
            {
                if (data == null)
                {
                    this.stop(false);
                    return;
                }
                ThingUtil.selectEntity = ThingUtil.npcUtil.getNpc(int(data.params));
                if (ThingUtil.selectEntity == null)
                {
                    this.stop(false);
                    return;
                }
            }
            Cache.instance.npc.isBySceneClick = data.target as Boolean;
            Dispatcher.dispatchEvent(new DataEvent(EventName.NPC_ClickedHandler, ThingUtil.selectEntity));
            Cache.instance.npc.isBySceneClick = false;
            this.stop(false);
            return;
        }// end function

        override public function stop(param1:Boolean = true) : void
        {
            super.stop(param1);
            if (this._turnTimerId > 0)
            {
                clearTimeout(this._turnTimerId);
                this._turnTimerId = -1;
            }
            return;
        }// end function

    }
}
